package com.ruoyi.web.controller.prod;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.ERP.BomInfoErp;
import com.ruoyi.system.domain.HUAWEI.EntityRevisionDTO;
import com.ruoyi.system.domain.HUAWEI.Software;
import com.ruoyi.system.domain.SetModel;
import com.ruoyi.system.domain.WMS.WmsQtMaterial;
import com.ruoyi.system.domain.base.BaseCustomer;
import com.ruoyi.system.domain.base.BaseMaterial;
import com.ruoyi.system.domain.base.BaseShop;
import com.ruoyi.system.domain.base.MesOperations;
import com.ruoyi.system.domain.function.ProdOrderDTO;
import com.ruoyi.system.domain.function.ProdPlan;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IProdOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IProdPlanService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 生产计划Controller
 *
 * @author ruoyi
 * @date 2023-02-13
 */
@Api(tags = "生产计划api")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/prod/plan" )
public class ProdPlanController extends BaseController {

    private final IProdPlanService iProdPlanService;
    @Autowired
    private SetModelMapper setModelMapper;
    @Autowired
    private BaseMaterialMapper baseMaterialMapper;
    @Autowired
    private BaseShopMapper baseShopMapper;
    @Autowired
    private MesOperationsMapper mesOperationsMapper;
    @Autowired
    private BaseCustomerMapper baseCustomerMapper;


    /**
     * 查询生产计划列表
     */
    @ApiOperation(value = "查询生产计划列表")
    //@PreAuthorize("@ss.hasPermi('prod:plan:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProdPlan prodPlan)
    {
        startPage();
        LambdaQueryWrapper<ProdPlan> lqw = new LambdaQueryWrapper<ProdPlan>();
        if (StringUtils.isNotBlank(prodPlan.getPlanCode())){
            lqw.eq(ProdPlan::getPlanCode ,prodPlan.getPlanCode());
        }
        if (StringUtils.isNotBlank(prodPlan.getMaterialName())){
            lqw.like(ProdPlan::getMaterialName ,prodPlan.getMaterialName());
        }
        if (StringUtils.isNotBlank(prodPlan.getLineName())){
            lqw.like(ProdPlan::getLineName ,prodPlan.getLineName());
        }
        if (StringUtils.isNotBlank(prodPlan.getRoutingName())){
            lqw.like(ProdPlan::getRoutingName ,prodPlan.getRoutingName());
        }
        if (StringUtils.isNotBlank(prodPlan.getCustomerName())){
            lqw.like(ProdPlan::getCustomerName ,prodPlan.getCustomerName());
        }
        if (StringUtils.isNotBlank(prodPlan.getCustomerOrderNum())){
            lqw.eq(ProdPlan::getCustomerOrderNum ,prodPlan.getCustomerOrderNum());
        }
        if (StringUtils.isNotBlank(prodPlan.getTaskTon())){
            lqw.like(ProdPlan::getTaskTon ,prodPlan.getTaskTon());
        }
        if (prodPlan.getStartTime() != null){
            lqw.eq(ProdPlan::getStartTime ,prodPlan.getStartTime());
        }
        if (prodPlan.getEndTime() != null){
            lqw.eq(ProdPlan::getEndTime ,prodPlan.getEndTime());
        }
        if (prodPlan.getPlanState() != null){
            lqw.eq(ProdPlan::getPlanState ,prodPlan.getPlanState());
        }
        if (prodPlan.getComState() != null){
            lqw.eq(ProdPlan::getComState ,prodPlan.getComState());
        }
        lqw.orderByDesc(ProdPlan::getCreateTime);
        List<ProdPlan> list = iProdPlanService.list(lqw);
        return getDataTable(list);
    }


    /**
     * 查询生产计划列表
     */
    @ApiOperation(value = "查询生产计划列表")
    //@PreAuthorize("@ss.hasPermi('prod:plan:getBomInfoErpList')")
    @GetMapping("/getBomInfoErpList")
    public TableDataInfo getBomInfoErpList(BomInfoErp bomInfoErp)
    {
        startPage();
        List<BomInfoErp> list = iProdPlanService.getBomInfoErpList(bomInfoErp);
        return getDataTable(list);
    }

    /**
     * 导出生产计划列表
     */
    //@PreAuthorize("@ss.hasPermi('system:plan:export')" )
    @Log(title = "生产计划" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(ProdPlan prodPlan) {
        LambdaQueryWrapper<ProdPlan> lqw = new LambdaQueryWrapper<ProdPlan>(prodPlan);
        List<ProdPlan> list = iProdPlanService.list(lqw);
        ExcelUtil<ProdPlan> util = new ExcelUtil<ProdPlan>(ProdPlan. class);
        return util.exportExcel(list, "plan" );
    }

    /**
     * 获取生产计划详细信息
     */
    @ApiOperation(value = "获取生产计划详细信息")
    //@PreAuthorize("@ss.hasPermi('system:plan:query')" )
    @GetMapping(value = "/{planId}" )
    public AjaxResult getInfo(@PathVariable("planId" ) Long planId) {
        AjaxResult ajaxResult = iProdPlanService.getInfo(planId);
        return ajaxResult;
    }

    @ApiOperation(value = "获取工艺下拉数据")
    @GetMapping(value = "/getGy/{planId}" )
    public AjaxResult getGy(@PathVariable("planId" ) Long planId) {
        AjaxResult ajaxResult = iProdPlanService.getGy(planId);
        return ajaxResult;
    }



    /**
     * 新增生产计划
     */
    @ApiOperation(value = "新增生产计划")
    //@PreAuthorize("@ss.hasPermi('system:plan:add')" )
    @Log(title = "生产计划" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProdPlan prodPlan) {
        prodPlan.setCreateBy(SecurityUtils.getUsername());
        prodPlan.setCreateTime(new Date());
        prodPlan.setSurplusNumber(prodPlan.getPlanNumber()-prodPlan.getComNumber());
        //根据产品编码获取产品名称
        SetModel setModel = setModelMapper.selectOne(new QueryWrapper<SetModel>().eq("model_code", prodPlan.getProductCode()));
        if(ObjectUtil.isNotNull(setModel)){
            prodPlan.setProductName(setModel.getModel());
        }
        //根据物料编码获取物料名称
        BaseMaterial baseMaterial = baseMaterialMapper.selectOne(new QueryWrapper<BaseMaterial>().eq("material_code", prodPlan.getMaterialCode()));
        if(ObjectUtil.isNotNull(baseMaterial)){
            prodPlan.setMaterialName(baseMaterial.getMaterialName());
        }
        //根据产线编码获取产线名称
        BaseShop shop = baseShopMapper.selectOne(new QueryWrapper<BaseShop>().eq("shop_code", prodPlan.getLineCode()));
        if(ObjectUtil.isNotNull(shop)){
            prodPlan.setLineName(shop.getShopName());
        }
        //根据工艺路线编码获取工艺路线名称
        MesOperations mesOperations = mesOperationsMapper.selectOne(new QueryWrapper<MesOperations>().eq("operation_code", prodPlan.getRoutingCode()));
        if(ObjectUtil.isNotNull(mesOperations)){
            prodPlan.setRoutingName(mesOperations.getOperationName());
        }
        //根据客户编码获取客户名称
        BaseCustomer baseCustomer = baseCustomerMapper.selectOne(new QueryWrapper<BaseCustomer>().eq("customer_code", prodPlan.getCustomerCode()));
        if(ObjectUtil.isNotNull(baseCustomer)){
            prodPlan.setCustomerName(baseCustomer.getCustomerName());
        }
        return toAjax(iProdPlanService.save(prodPlan) ? 1 : 0);
    }

    /**
     * 修改生产计划
     */
    @ApiOperation(value = "修改生产计划")
    //@PreAuthorize("@ss.hasPermi('system:plan:edit')" )
    @Log(title = "生产计划" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProdPlan prodPlan) {
        prodPlan.setUpdateBy(SecurityUtils.getUsername());
        prodPlan.setUpdateTime(new Date());
        prodPlan.setSurplusNumber(prodPlan.getPlanNumber()-prodPlan.getComNumber());

        //根据产品编码获取产品名称
        SetModel setModel = setModelMapper.selectOne(new QueryWrapper<SetModel>().eq("model_des_local_code", prodPlan.getProductCode()));
        if(ObjectUtil.isNotNull(setModel)){
            prodPlan.setProductName(setModel.getLedName());
        }
        //根据物料编码获取物料名称
        BaseMaterial baseMaterial = baseMaterialMapper.selectOne(new QueryWrapper<BaseMaterial>().eq("material_code", prodPlan.getMaterialCode()));
        if(ObjectUtil.isNotNull(baseMaterial)){
            prodPlan.setMaterialName(baseMaterial.getMaterialName());
        }
        //根据产线编码获取产线名称
        BaseShop shop = baseShopMapper.selectOne(new QueryWrapper<BaseShop>().eq("shop_code", prodPlan.getLineCode()));
        if(ObjectUtil.isNotNull(shop)){
            prodPlan.setLineName(shop.getShopName());
        }
        //根据工艺路线编码获取工艺路线名称
        MesOperations mesOperations = mesOperationsMapper.selectOne(new QueryWrapper<MesOperations>().eq("operation_code", prodPlan.getRoutingCode()));
        if(ObjectUtil.isNotNull(mesOperations)){
            prodPlan.setRoutingName(mesOperations.getOperationName());
        }
        //根据客户编码获取客户名称
        BaseCustomer baseCustomer = baseCustomerMapper.selectOne(new QueryWrapper<BaseCustomer>().eq("customer_code", prodPlan.getCustomerCode()));
        if(ObjectUtil.isNotNull(baseCustomer)){
            prodPlan.setCustomerName(baseCustomer.getCustomerName());
        }

        return toAjax(iProdPlanService.updateById(prodPlan) ? 1 : 0);
    }

    /**
     * 删除生产计划
     */
    @ApiOperation(value = "删除生产计划")
    //@PreAuthorize("@ss.hasPermi('system:plan:remove')" )
    @Log(title = "生产计划" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{planIds}" )
    public AjaxResult remove(@PathVariable Long[] planIds) {
        return toAjax(iProdPlanService.removeByIds(Arrays.asList(planIds)) ? 1 : 0);
    }

    @ApiOperation(value = "工单下发")
    @RequestMapping(value = "/issued", method = RequestMethod.POST)
    public AjaxResult issued(@RequestBody ProdOrderDTO dto) {
        AjaxResult ajaxResult = iProdPlanService.issued(dto);
        return ajaxResult;
    }

    @ApiOperation(value = "齐套校验")
    @RequestMapping(value = "/qtjy", method = RequestMethod.POST)
    public AjaxResult qtjy(@RequestBody ProdOrderDTO dto) {
        AjaxResult ajaxResult = iProdPlanService.qtjy(dto);
        return ajaxResult;
    }

    @ApiOperation(value = "齐套校验详情")
    @RequestMapping(value = "/qtjyInfo", method = RequestMethod.GET)
    public TableDataInfo qtjyInfo(ProdOrderDTO dto) {
        startPage();
        List<WmsQtMaterial> list = iProdPlanService.qtjyInfo(dto);
        return getDataTable(list);
    }

    @ApiOperation(value = "生产计划拆分工单")
    @RequestMapping(value = "/createProd", method = RequestMethod.POST)
    public AjaxResult createProd(@RequestBody ProdOrderDTO dto) {
        return AjaxResult.success(iProdPlanService.createProd(dto));
    }

    @ApiOperation(value = "定时比对总成生产（测试入口）")
    @RequestMapping(value = "/planZcCom/{rule}", method = RequestMethod.GET)
    public AjaxResult planCom(@PathVariable Integer rule) {
        iProdPlanService.planCom(rule);
        return AjaxResult.success();
    }

    @ApiOperation(value = "定时比对Bomm明细生产（测试入口）")
    @RequestMapping(value = "/planBomCom/{rule}", method = RequestMethod.GET)
    public AjaxResult planBomCom(@PathVariable Integer rule) {
        iProdPlanService.planBomCom(rule);
        return AjaxResult.success();
    }


    @ApiOperation(value = "获取任务令版本信息",response = Software.class)
    @RequestMapping(value = "/getPoversion", method = RequestMethod.GET)
    public AjaxResult getPoversion(@RequestParam String taskTon) {
        return iProdPlanService.getPoversion(taskTon);
    }

    @ApiOperation(value = "任务令版本信息上传")
    @RequestMapping(value = "/uploadPoversion", method = RequestMethod.POST)
    public AjaxResult uploadPoversion(@RequestBody List<Software> list) {
        return iProdPlanService.uploadPoversion(list);
    }


}
